package com.fouram.agent.util;

import javassist.CtMethod;

import java.util.*;

/**
 * PojoDetector
 * @author fouram
 */
public class PojoDetector {

    private final static String METHOD_GET = "get";
    private final static String METHOD_SET = "set";
    private final static String METHOD_IS = "is";
    
    public static Set<String> getPojoMethodNames(CtMethod[] methods){
        Set<String> pojoMethods = Collections.emptySet();
        if(null != methods && methods.length>0){
            pojoMethods = new HashSet<>();
            Map<String,String> propName2MethodName = new HashMap<>(8);
            for(CtMethod method : methods){
                String methodName = method.getName();
                if(isSetMethod(methodName) || isGetMethod(methodName)){
                    String propName = getPojoPropertyName(methodName);
                    if(propName2MethodName.containsKey(propName)){
                        pojoMethods.add(methodName);
                        pojoMethods.add(propName2MethodName.get(propName));
                    }else{
                        propName2MethodName.put(propName, methodName);
                    }
                }
            }
        }
        return pojoMethods;
    }

    private static boolean isGetMethod(String methodName){
        return methodName.startsWith(METHOD_GET) || methodName.startsWith(METHOD_IS);
    }
    
    private static boolean isSetMethod(String methodName){
        return methodName.startsWith(METHOD_SET);
    }
    
    private static String getPojoPropertyName(String methodName){
        if(methodName.startsWith(METHOD_GET) || methodName.startsWith(METHOD_SET)){
            return methodName.substring(3);
        }else if(methodName.startsWith(METHOD_IS)){
            return methodName.substring(2);
        }
        return "";
    }
}
